<template>
  <div class="loginpage">
    <div class="signUp">
      <div class="registermain">
        <div class="back-icon" @click="router.push('/login')">
          <van-icon name="arrow-left" size="20" color="#f6eade" />
        </div>
        <div class="mt-5 register-title">
          <h3>{{ t("logintxt.register01") }}</h3>
        </div>
        <div class="register-form">
          <van-form :model="postData" :validate-trigger="[]" @submit="register">
            <!-- 手机号输入 -->
            <div class="overflow-hidden rounded-3xl phone-input-wrapper">
              <div class="user-icon-container">
                <van-icon
                  name="manager-o"
                  size="18"
                  color="#f6eade"
                  class="mb-5"
                />
              </div>
              <div class="phone-area-code" @click="showAreaCodePicker = true">
                <span>+ {{ currentAreaCode }}</span>
                <van-icon name="arrow-down" size="14" />
              </div>
              <van-field
                v-model="postData.tel"
                name="tel"
                type="number"
                :formatter="removeSpace"
                :placeholder="t('logintxt.login02')"
                class="phone-input"
              />
            </div>

            <!-- 密码输入 -->
            <div class="mt-16 overflow-hidden rounded-3xl">
              <van-field
                v-model="postData.loginPassword"
                :type="showPassword ? 'text' : 'password'"
                name="loginPassword"
                :placeholder="t('logintxt.login03')"
                :formatter="removeSpace"
                class="password-input"
              >
                <template #left-icon>
                  <div class="user-icon-container">
                    <van-icon
                      name="lock"
                      size="18"
                      color="#f6eade"
                      class="mb-5"
                    />
                  </div>
                </template>
                <template #right-icon>
                  <van-icon
                    :name="showPassword ? 'eye-o' : 'closed-eye'"
                    size="20"
                    @click="showPassword = !showPassword"
                    color="#f6eade"
                  />
                </template>
              </van-field>
            </div>

            <!-- 邀请码输入 -->
            <div class="mt-16 overflow-hidden rounded-3xl">
              <van-field
                v-model="postData.parent"
                name="parent"
                :placeholder="t('logintxt.register02')"
                :formatter="removeSpace"
                class="invite-input"
              >
                <template #left-icon>
                  <div class="user-icon-container">
                    <img
                      src="@/assets/images/login/iconMail.png"
                      class="icon-img mb-5"
                      alt="mail icon"
                    />
                  </div>
                </template>
              </van-field>
            </div>

            <!-- 验证码输入 -->
            <div class="mt-16 overflow-hidden rounded-3xl">
              <van-field
                v-model="postData.verificationCode"
                name="verificationCode"
                :placeholder="t('logintxt.register03')"
                class="verification-input"
              >
                <template #left-icon>
                  <div class="user-icon-container">
                    <img
                      src="@/assets/images/login/iconCode.png"
                      class="icon-img mb-5"
                      alt="mail icon"
                    />
                  </div>
                </template>
                <template #right-icon>
                  <div
                    class="verification-code"
                    @click="refreshVerificationCode"
                  >
                    {{ verificationDisplay }}
                  </div>
                </template>
              </van-field>
            </div>

            <!-- 隐私协议 -->
            <div class="mt-16 privacy-agreement">
              <p>
                {{ t("logintxt.register04") }}
                <span class="privacy-link">{{ t("logintxt.register05") }}</span
                >.
              </p>
            </div>

            <!-- 注册按钮 -->
            <div class="mt-16">
              <van-button
                :loading="loading"
                native-type="submit"
                round
                block
                class="register-btn"
              >
                {{ t("logintxt.register06") }}
              </van-button>
            </div>
            <GhostButton
              block
              to="login"
              :style="{ 'margin-top': vw(18) }"
              class="register-button"
            >
              <span class="register-text">{{ t("logintxt.login071") }}</span>
              <span class="register-link">{{ t("login") }}</span>
            </GhostButton>
            <!-- Google注册按钮 -->
            <div class="mt-16" style="display: none">
              <van-button
                round
                block
                class="google-register-btn"
                @click="registerWithGoogle"
              >
                <div class="google-btn-content">
                  <img
                    src="@/assets/images/login/iconG.png"
                    class="google-icon"
                    alt="Google"
                  />
                  <span>{{ t("logintxt.login06") }}</span>
                </div>
              </van-button>
            </div>
          </van-form>

          <!-- 隐私政策 -->
        </div>
      </div>

      <!-- 区号选择弹窗 -->
      <van-popup v-model:show="showAreaCodePicker" position="bottom" round>
        <van-picker
          :title="t('logintxt.login10')"
          :columns="areaCodeOptions"
          @confirm="onAreaCodeConfirm"
          @cancel="showAreaCodePicker = false"
          show-toolbar
        />
      </van-popup>
    </div>
  </div>
</template>

<script setup lang="ts">
import { areaCodeApi } from "@/api/login";
import { useUserStore } from "@/stores";
import { showDialog, showNotify } from "vant";
import { onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import vw from "@/utils/inline-px-to-vw";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const loading = ref(false);
const showAreaCodePicker = ref(false);
const showPassword = ref(false);

// 区号选择配置 - 改为动态获取
const areaCodeOptions = ref([
  { text: "+57", value: "57" },
  // { text: '中国 +86', value: '86' },
  // { text: '马来西亚 +60', value: '60' },
  // { text: '新加坡 +65', value: '65' },
  // { text: '泰国 +66', value: '66' }
]);

// 当前选中的区号
const currentAreaCode = ref("57");

// 获取区号列表
async function getAreaCodes() {
  try {
    const { data } = await areaCodeApi();
    if (data && Array.isArray(data)) {
      // 将API返回的区号数据转换为选择器需要的格式
      areaCodeOptions.value = data.map((item: any) => {
        return {
          text: `${item.country || ""} +${item.mobilePrefix}`,
          value: item.mobilePrefix,
        };
      });

      // 如果用户没有选择区号，则设置默认区号
      if (!postData.areaCode && areaCodeOptions.value.length > 0) {
        const defaultOption = areaCodeOptions.value[0];
        postData.areaCode = defaultOption.value;
        currentAreaCode.value = defaultOption.value;
      }
    }
  } catch (error) {
    console.error("获取区号列表失败:", error);
    // 确保至少有一个默认选项
    if (areaCodeOptions.value.length === 0) {
      areaCodeOptions.value = [{ text: "+57", value: "57" }];
      if (!postData.areaCode) {
        postData.areaCode = "57";
        currentAreaCode.value = "57";
      }
    }
  }
}

function onAreaCodeConfirm(result: any) {
  console.log(result);

  // 处理新的选择器返回格式
  if (result.selectedOptions && result.selectedOptions.length > 0) {
    // 新格式
    const selectedOption = result.selectedOptions[0];
    postData.areaCode = selectedOption.value;
    currentAreaCode.value = selectedOption.value;
  } else if (result.value) {
    // 旧格式兼容处理
    postData.areaCode = result.value;
    currentAreaCode.value = result.value;
  }

  showAreaCodePicker.value = false;
}

function removeSpace(value: string) {
  return value.replace(/\s+/g, "");
}


const postData = reactive({
  areaCode: "", // 默认留空，由获取区号接口设置默认值
  tel: "",
  loginPassword: "",
  parent: "",
  verificationCode: "", // 用于验证码验证，但不是API必需参数
});

// 使用自定义验证函数，而不是规则数组
function validatePhoneNumber() {
  if (!postData.tel) {
    showDialog({
      message: t("logintxt.login02"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  // 添加电话号码格式验证
  const phoneRegex = /^\d{9,12}$/; // 9-12位数字
  if (!phoneRegex.test(postData.tel)) {
    showDialog({
      message: t("logintxt.register08"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  return true;
}

function validatePassword() {
  if (!postData.loginPassword) {
    showDialog({
      message: t("logintxt.login03"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  // 添加密码长度验证
  if (postData.loginPassword.length < 6) {
    showDialog({
      message: t("logintxt.register09"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  return true;
}

// 验证验证码
function validateVerificationCode() {
  console.log(123123);
  
  if (!postData.verificationCode) {
    showDialog({
      message: t("logintxt.register10"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  // 简单验证，实际应该从后端验证 - 不区分大小写
  if (
    postData.verificationCode.toUpperCase() !==
    verificationDisplay.value.toUpperCase()
  ) {
    showDialog({
      message: t("logintxt.register11"),
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
    return false;
  }

  return true;
}

// 由于我们使用自定义验证，这里可以保留空规则
const rules = reactive({
  tel: [],
  loginPassword: [],
});

// 验证码显示
const verificationDisplay = ref("BLVN");

// 生成随机验证码
function generateVerificationCode(length = 4) {
  const characters = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 排除容易混淆的字符 I, O, 0, 1
  let result = "";
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

// 刷新验证码
function refreshVerificationCode() {
  verificationDisplay.value = generateVerificationCode();
}

// 页面加载时获取区号和生成验证码，并获取URL参数
onMounted(() => {
  // 设置默认区号
  postData.areaCode = "57";
  currentAreaCode.value = "57";

  // 获取区号列表
  getAreaCodes();

  // 生成初始验证码
  refreshVerificationCode();

  // 获取URL中的邀请码参数
  const code = route.query.code;
  if (code && typeof code === "string") {
    postData.parent = code;
  }
});

async function register() {
  // 手动验证
  if (
    !validatePhoneNumber() ||
    !validatePassword() ||
    !validateVerificationCode()
  ) {
    return;
  }

  try {
    loading.value = true;

    // 构建注册参数
    const registerData = {
      tel: postData.tel,
      areaCode: postData.areaCode,
      loginPassword: postData.loginPassword.replace(/\s+/g, ""),
      parent: postData.parent || "", // 邀请码可以为空
    };

    // 这里调用注册API
    let res = await userStore.register(registerData);
    console.log(res);

    if (res.code == 200) {
      // 注册成功后处理
      showNotify({ type: "success", message: t("logintxt.register13") });
      router.replace("/login");
    } else {
      showNotify({ type: "warning", message: res.msg });
    }
  } catch (error: any) {
    // 处理注册失败情况
    const errorMessage = error?.message || t("logintxt.register12");
    showDialog({
      message: errorMessage,
      confirmButtonText: t("logintxt.register07"),
      confirmButtonColor: "#3f88f5",
      className: "custom-dialog",
      showCancelButton: false,
      closeOnClickOverlay: true,
    });
  } finally {
    loading.value = false;
  }
}

function registerWithGoogle() {
  console.log("Google");
}
</script>

<style lang="less" scoped>
.loginpage {
  background-color: #221a18;
}

:deep(.custom-dialog) {
  background-color: #ffffff !important;
  border-radius: 8px !important;

  .van-dialog__header {
    display: none;
  }

  .van-dialog__content {
    color: #333 !important;
    padding: 30px 20px;
  }

  .van-dialog__message {
    color: #333 !important;
    font-size: 16px;
    padding: 0;
    text-align: center;
  }

  .van-button {
    height: 40px;
    font-size: 16px;
    border-radius: 6px;
  }

  .van-dialog__footer {
    padding: 0 20px 20px;
  }
}

.signUp {
  background-image: url("@/assets/images/login/topBg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  min-height: 100vh;
  position: relative;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 15px;
  padding: 8px;
  z-index: 100;
}

.registermain {
  padding-top: 52px;
  display: flex;
  flex-direction: column;
  flex: 1;
  margin: 20px 30px 0 30px;
}

.register-title {
  width: 100%;
  overflow: hidden;
  padding: 5px 0;
  font-size: 15px;
  color: transparent;
  background: linear-gradient(112deg, #f9f3ed 14%, #fad4b7 88%), #ffe6ce;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;

  h3 {
    margin: 0 0 15px 0;
  }
}

.register-form {
  width: 100%;
  height: auto;
  overflow: hidden;
  padding: 20px 15px;
  font-size: 15px;
  background: url("@/assets/images/login/loginBg.png") no-repeat top;
  background-size: 100% auto;
}

.phone-input-wrapper,
.password-input,
.invite-input,
.verification-input {
  display: flex;
  align-items: center;
  background-color: #1c1c1e;
  border-radius: 12px;
  height: 48px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
  padding-left: 0px;
}

.user-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 5px 0 10px;

  .icon-img {
    width: 18px;
    height: 18px;
    object-fit: contain;
  }
}

.phone-area-code {
  display: flex;
  align-items: center;
  padding: 0 5px 0 15px;
  height: 100%;
  color: #f6eade;
  font-size: 14px;
  font-weight: 500;
  border-right: 0px solid #d6c4a4;

  span {
    margin-right: 4px;
    font-size: 16px;
  }
}

.phone-input {
  flex: 1;
  background-color: transparent;

  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0px;
    font-size: 16px;
  }

  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.password-input,
.invite-input,
.verification-input {
  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 10px;
    font-size: 16px;
  }

  :deep(.van-field__right-icon) {
    color: #f6eade;
    padding-right: 15px;
  }

  :deep(.van-field__left-icon) {
    padding: 0;
  }

  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.verification-code {
  padding: 0 15px;
  color: #9b85fb;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 2px;
}

.privacy-agreement {
  font-size: 12px;
  text-align: left;
  p {
    color: #999;
  }
  .privacy-link {
    color: #fff;
    font-size: 12px;
  }
}

.register-btn {
  color: #0c1f26;
  font-weight: 500;
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border-radius: 12px;
  box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.3);
  border: none;
  height: 44px;

  :deep(.van-button__content) {
    color: #0c1f26;
    font-weight: 600;
    font-size: 16px;
  }

  &:active {
    opacity: 0.9;
  }

  &.van-button--loading {
    .van-loading__spinner {
      color: #0c1f26;
    }
  }
}

.google-register-btn {
  background:
    linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf),
    linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border-radius: 12px;
  color: #0c1f26;
  border: 1px solid #d6c4a4;
  height: 44px;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);

  :deep(.van-button__content) {
    padding: 0;
  }

  .google-btn-content {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;

    span {
      font-size: 14px;
      font-weight: 600;
      color: #0c1f26;
    }
  }

  .google-icon {
    width: 18px;
    height: 18px;
    margin-right: 8px;
    object-fit: contain;
  }

  &:active {
    opacity: 0.9;
  }
}

.privacy-policy-container {
  width: 100%;
  text-align: center;
  padding: 16px 0;
  position: fixed;
  bottom: 0;
  left: 0;
}

.privacy-policy-link {
  color: #d6c4a4;
  opacity: 0.8;
  font-size: 12px;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}
</style>
